package com.qiantu.phone.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.hjq.base.BaseDialog;
import com.hjq.base.DensityUtils;
import com.hjq.http.listener.HttpCallback;
import com.hjq.umeng.UmengClient;
import com.hjq.widget.layout.SettingBar;
import com.hjq.widget.view.SwitchButton;
import com.qiantu.api.db.LLControllerDBManager;
import com.qiantu.api.entity.ControllerBean;
import com.qiantu.api.entity.SettingBean;
import com.qiantu.api.http.HttpBaseData;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.BuildConfig;
import com.qiantu.phone.R;
import com.qiantu.phone.aop.Log;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.app.AppConfig;
import com.qiantu.phone.event.LanModeChangeEvent;
import com.qiantu.phone.ui.dialog.ConfirmCancelHintDialog;
import com.qiantu.phone.utils.CacheUtil;
import com.qiantu.phone.utils.PhoneUUIDUtils;
import com.qiantu.phone.utils.SPUtils;
import com.qiantu.phone.utils.StringUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.concurrent.Callable;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;

/**
 * time   : 2021/12/22
 */
public final class SettingActivity extends AppActivity {

    private static final int EDIT_SMART_MODE_CODE = 0x1;
    private static final int EDIT_TOUCH_FEEDBACK_CODE = 0x2;
    private SettingBar itemAccount;
    private SettingBar itemSmartMode;
    private SettingBar itemThemeSetting;
    private SettingBar itemTouchFeedback;
    private SettingBar itemClearCache;
    private SwitchButton btnAgingAdaptationSwitch;
    private SwitchButton btnWifiAutoUpdateSwitch;
    private SwitchButton btnLanSwitch;
    private TextView tvLanHints;
    private SettingBean mSettingBean;

    @Log
    public static void start(Context context) {
        Intent intent = new Intent(context, SettingActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.setting_activity;
    }

    @Override
    protected void initView() {
        UmengClient.init(AppApplication.getInstance(), AppConfig.isLogEnable());
        itemAccount = findViewById(R.id.item_account);
        itemSmartMode = findViewById(R.id.item_smart_mode);
        btnAgingAdaptationSwitch = findViewById(R.id.btn_aging_adaptation_switch);
        itemTouchFeedback = findViewById(R.id.item_touch_feedback);
        itemClearCache = findViewById(R.id.item_clear_cache);
        btnWifiAutoUpdateSwitch = findViewById(R.id.btn_wifi_auto_update_switch);
        btnLanSwitch = findViewById(R.id.btn_lan_switch);
        tvLanHints = findViewById(R.id.lan_hint);
        setOnClickListener(R.id.item_transfer_animation_setting, R.id.item_account, R.id.item_pager_custom, R.id.item_smart_mode, R.id.btn_aging_adaptation_switch, R.id.item_touch_feedback, R.id.item_message_setting, R.id.item_clear_cache, R.id.btn_wifi_auto_update_switch, R.id.btn_lan_switch, R.id.btn_logout,R.id.item_openpage_setting,R.id.item_version_update);
        setCacheData();
        if(AppApplication.getInstance().getCurHouseInfo().getRoleType() == 2){
            findViewById(R.id.item_message_setting).setVisibility(View.GONE);
            findViewById(R.id.item_version_update).setVisibility(View.GONE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getSettingData();
    }

    private void getSettingData(){
        btnLanSwitch.setChecked(HttpBaseData.getInstance().isLanMode);
        tvLanHints.setVisibility(HttpBaseData.getInstance().isLanMode ? View.VISIBLE : View.GONE);
        if(HttpBaseData.getInstance().isLanMode){
            return;
        }
        LLHttpManager.getAllSetting(this, new HttpCallback<HttpData<SettingBean>>(this) {

            @Override
            public void onStart(Call call) {
                showDialog(getString(R.string.common_loading));
            }

            @Override
            public void onSucceed(HttpData<SettingBean> result) {
                AppApplication.getInstance().mSettingBean = result.getData();
                mSettingBean = AppApplication.getInstance().mSettingBean;
                updateView();
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                hideDialog();
            }
        });
        itemAccount.setRightText(StringUtil.replacePhoneNum2Star(AppApplication.getInstance().getUserPhone()));
    }

    @Override
    protected void initData() {

    }

    private void updateView() {
        itemAccount.setRightText(StringUtil.replacePhoneNum2Star(mSettingBean.getPhone()));
        updateSmartModeView();
        btnAgingAdaptationSwitch.setChecked(mSettingBean.getSetting().isAgingAdaptation());
        updateTouchFeedView();
        btnWifiAutoUpdateSwitch.setChecked(mSettingBean.getSetting().isDownloadInWifi());
    }

    private void updateSmartModeView(){
        switch (mSettingBean.getSetting().getIntelligentControlMode().getControlMode()) {
            case 1:
                itemSmartMode.setRightText(R.string.normal_mode);
                break;
            case 2:
                itemSmartMode.setRightText(R.string.local_mode);
                break;
        }
    }

    private void updateTouchFeedView(){
        String touchFeedback = "";
        if (mSettingBean.getSetting().getTouchFeedback().isFollowSystem()) {
            touchFeedback = getString(R.string.follow_system);
        } else {
            if (mSettingBean.getSetting().getTouchFeedback().isShock()) {
                touchFeedback = getString(R.string.vibrate);
            }
            if (mSettingBean.getSetting().getTouchFeedback().isVoice()) {
                String soundEffect = getString(R.string.sound_effect);
                touchFeedback = TextUtils.isEmpty(touchFeedback) ? soundEffect : touchFeedback + "/" + soundEffect;
            }
        }
        itemTouchFeedback.setRightText(touchFeedback);
    }

    private void setCacheData() {
        Observable.fromCallable(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return CacheUtil.getTotalCacheSize(SettingActivity.this);
            }
        }).subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        itemClearCache.setRightText(s);
                    }
                });
    }

    private BaseDialog mConfirmCancelHintDialog;
    private ConfirmCancelHintDialog.Builder mConfirmCancelHintDialogBuilder;

    private void showLogoutHintDialog() {
        if (mConfirmCancelHintDialog == null) {
            mConfirmCancelHintDialogBuilder = new ConfirmCancelHintDialog.Builder(getActivity());
            mConfirmCancelHintDialog = mConfirmCancelHintDialogBuilder.create();
        }
        mConfirmCancelHintDialogBuilder.setContent(getString(R.string.logout_hint));
        mConfirmCancelHintDialogBuilder.setRightText(R.string.logout);
        mConfirmCancelHintDialogBuilder.setListener(new ConfirmCancelHintDialog.OnListener() {
            @Override
            public void onLeftClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
            }

            @Override
            public void onRightClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
                String androidId = PhoneUUIDUtils.getDeviceUUID(AppApplication.getInstance());
                LLHttpManager.logout(SettingActivity.this, androidId, AppApplication.getInstance().pushDeviceId, new HttpCallback<HttpData<Void>>(null){
                    @Override
                    public void onStart(Call call) {
                        showDialog(getString(R.string.exiting));
                    }

                    @Override
                    public void onSucceed(HttpData<Void> result) {
                        AppApplication.getInstance().logoutToLogin();
                    }

                    @Override
                    public void onFail(Exception e) {
                        toast(R.string.exit_failed);
                    }

                    @Override
                    public void onEnd(Call call) {
                        hideDialog();
                    }
                });
            }
        });
        mConfirmCancelHintDialog.show();
    }

    @Override
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.item_transfer_animation_setting:
                intent = new Intent(this, TransferAnimationActivity.class);
                startActivity(intent);
                break;
            case R.id.item_account:
                startActivity(AccountManagerActivity.class);
                break;
            case R.id.item_pager_custom:
                intent = new Intent(this, PagerCustomActivity.class);
                startActivity(intent);
                break;
            case R.id.item_smart_mode:
                intent = new Intent(this, SmartModeActivity.class);
                intent.putExtra("controlMode", mSettingBean.getSetting().getIntelligentControlMode().getControlMode());
                startActivityForResult(intent, EDIT_SMART_MODE_CODE);
                break;
            case R.id.item_touch_feedback:
                intent = new Intent(this, TouchFeedbackActivity.class);
                intent.putExtra("isFollowSystem", mSettingBean.getSetting().getTouchFeedback().isFollowSystem());
                intent.putExtra("isShock", mSettingBean.getSetting().getTouchFeedback().isShock());
                intent.putExtra("isVoice", mSettingBean.getSetting().getTouchFeedback().isVoice());
                startActivityForResult(intent, EDIT_TOUCH_FEEDBACK_CODE);
                break;
            case R.id.item_message_setting:
                intent = new Intent(this, MessageSettingActivity.class);
                startActivity(intent);
                break;
            case R.id.item_clear_cache:
                clearCache();
                break;
            case R.id.btn_aging_adaptation_switch:
                boolean isAgingAdaptation = btnAgingAdaptationSwitch.isChecked();
                btnAgingAdaptationSwitch.setChecked(!isAgingAdaptation);
                setAgingAdaptation(isAgingAdaptation);
                break;
            case R.id.btn_wifi_auto_update_switch:
                boolean isWifiAutoUpdate = btnWifiAutoUpdateSwitch.isChecked();
                btnWifiAutoUpdateSwitch.setChecked(!isWifiAutoUpdate);
                setWifiAutoUpdate(isWifiAutoUpdate);
                break;
            case R.id.btn_logout:
                showLogoutHintDialog();
                break;
            case R.id.item_openpage_setting:
                gotoOpenPage();
                break;
            case R.id.btn_lan_switch:
                if(btnLanSwitch.isChecked()){
                    List<ControllerBean> controllerBeanList = LLControllerDBManager.getInstance(getContext()).getControllersByProductModel("0x1501");
                    if(controllerBeanList.size() >0){
                        HttpBaseData.getInstance().setLanIP(controllerBeanList.get(0).getIp());
                        SPUtils.getInstance().put("lan_mode_ip",controllerBeanList.get(0).getIp());
                    }
                }
                HttpBaseData.getInstance().setLanMode(btnLanSwitch.isChecked());
                SPUtils.getInstance().put("lan_mode",btnLanSwitch.isChecked());
                tvLanHints.setVisibility(btnLanSwitch.isChecked() ? View.VISIBLE : View.GONE);
                EventBus.getDefault().post(new LanModeChangeEvent(btnLanSwitch.isChecked()));
                break;
            case R.id.item_version_update:
                int androidHeight1 = DensityUtils.getStatusBarHeight(getActivity()) + getResources().getDimensionPixelSize(R.dimen.dp_16);
                StringBuilder stringBuilder1 = new StringBuilder(BuildConfig.UPDATE_SOFT_URL);
                stringBuilder1.append("/firmwareUpgrade").append("/?token=").append(AppApplication.getInstance().getLoginInfo().getToken())
                        .append("&houseId=").append(AppApplication.getInstance().getCurrentHouseSerialNo())
                        .append("&androidHeight=").append("'" + androidHeight1 + "'")
                        .append("&phoneType=").append("android")
                        .append("&phone=").append(AppApplication.getInstance().getLoginInfo().getUserInfo().getPhone());
                BrowserActivity.start(getContext(), stringBuilder1.toString());
                break;
        }
    }

    private void gotoOpenPage(){
        Intent intent = new Intent(this, OpenPageSettingActivity.class);
        startActivity(intent);

    }

    private void setWifiAutoUpdate(boolean isWifiAutoUpdate) {
        LLHttpManager.setDownloadWifi(this, isWifiAutoUpdate, new HttpCallback<HttpData<Void>>(this) {
            @Override
            public void onStart(Call call) {
                showDialog(getString(R.string.setting));
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                toast(R.string.set_success);
                btnWifiAutoUpdateSwitch.setChecked(isWifiAutoUpdate);
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                hideDialog();
            }
        });
    }

    private void setAgingAdaptation(boolean isAgingAdaptation) {
        LLHttpManager.setAgingAdaptation(this, isAgingAdaptation, new HttpCallback<HttpData<Void>>(this) {
            @Override
            public void onStart(Call call) {
                showDialog(getString(R.string.setting));
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                toast(R.string.set_success);
                btnAgingAdaptationSwitch.setChecked(isAgingAdaptation);
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                hideDialog();
            }
        });
    }

    private void clearCache() {
        if (mConfirmCancelHintDialog == null) {
            mConfirmCancelHintDialogBuilder = new ConfirmCancelHintDialog.Builder(getActivity());
            mConfirmCancelHintDialog = mConfirmCancelHintDialogBuilder.create();
        }
        mConfirmCancelHintDialogBuilder.setContent(getString(R.string.clear_cache_hint));
        mConfirmCancelHintDialogBuilder.setRightText(R.string.common_confirm);
        mConfirmCancelHintDialogBuilder.setListener(new ConfirmCancelHintDialog.OnListener() {
            @Override
            public void onLeftClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
            }

            @Override
            public void onRightClick(BaseDialog dialog) {
                mConfirmCancelHintDialogBuilder.dismiss();
                Observable.fromCallable(new Callable<Boolean>() {
                    @Override
                    public Boolean call() throws Exception {
                        CacheUtil.clearAllCache(SettingActivity.this);
                        return true;
                    }
                }).subscribeOn(Schedulers.computation())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {
                                toast(R.string.clear_success);
                                itemClearCache.setRightText("0KB");
                            }
                        });
            }
        });
        mConfirmCancelHintDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 友盟回调
        UmengClient.onActivityResult(this, requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case EDIT_SMART_MODE_CODE:
                int controlMode = data.getIntExtra("controlMode", 0);
                mSettingBean.getSetting().getIntelligentControlMode().setControlMode(controlMode);
                updateSmartModeView();
                break;
            case EDIT_TOUCH_FEEDBACK_CODE:
                boolean isFollowSystem = data.getBooleanExtra("isFollowSystem", false);
                boolean isShock = data.getBooleanExtra("isShock", false);
                boolean isVoice = data.getBooleanExtra("isVoice", false);
                mSettingBean.getSetting().getTouchFeedback().setFollowSystem(isFollowSystem);
                mSettingBean.getSetting().getTouchFeedback().setShock(isShock);
                mSettingBean.getSetting().getTouchFeedback().setVoice(isVoice);
                updateTouchFeedView();
                break;
        }
    }
}